package us.wili.dev.client.config;

import cn.binarywang.wx.miniapp.api.WxMaService;
import cn.binarywang.wx.miniapp.api.impl.WxMaServiceImpl;
import cn.binarywang.wx.miniapp.config.WxMaConfig;
import cn.binarywang.wx.miniapp.config.WxMaInMemoryConfig;
import me.chanjar.weixin.mp.api.WxMpInMemoryConfigStorage;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.api.impl.WxMpServiceImpl;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import us.wili.dev.client.config.properties.WechatMiniAppConfigProperties;

/**
 * @author wkx
 * @date 2018/9/4 09:59
 */
@Configuration
@EnableConfigurationProperties(WechatMiniAppConfigProperties.class)
public class WechatConfig {

    @Bean
    public WxMaInMemoryConfig wxMaInMemoryConfig(WechatMiniAppConfigProperties wechatMiniAppConfigProperties) {
        WxMaInMemoryConfig config = new WxMaInMemoryConfig();

        config.setAppid(wechatMiniAppConfigProperties.getAppId());
        config.setSecret(wechatMiniAppConfigProperties.getSecret());
        config.setToken(wechatMiniAppConfigProperties.getToken());
        config.setAesKey(wechatMiniAppConfigProperties.getAesKey());

        return config;
    }

    @Bean
    @ConditionalOnMissingBean
    public WxMaService wxMaService(WxMaConfig maConfig) {
        WxMaService service = new WxMaServiceImpl();
        service.setWxMaConfig(maConfig);
        return service;
    }

    @Bean
    public WxMpInMemoryConfigStorage wxMpInMemoryConfigStorage(WechatMiniAppConfigProperties wechatMiniAppConfigProperties) {
        WxMpInMemoryConfigStorage wxMpInMemoryConfigStorage = new WxMpInMemoryConfigStorage();

        wxMpInMemoryConfigStorage.setAesKey(wechatMiniAppConfigProperties.getAesKey());
        wxMpInMemoryConfigStorage.setSecret(wechatMiniAppConfigProperties.getSecret());
        wxMpInMemoryConfigStorage.setToken(wechatMiniAppConfigProperties.getToken());
        wxMpInMemoryConfigStorage.setAppId(wechatMiniAppConfigProperties.getAppId());

        return wxMpInMemoryConfigStorage;
    }

    @Bean
    public WxMpService wxMpService(WxMpInMemoryConfigStorage wxMpInMemoryConfigStorage) {
        WxMpService wxMpService = new WxMpServiceImpl();
        wxMpService.setWxMpConfigStorage(wxMpInMemoryConfigStorage);

        return wxMpService;
    }

}
